// pages/study/study.js
const app = getApp()
var util = require("../../utils/utils.js");
var WxParse = require("../../wxParse/wxParse.js");

function getRandomColor() {
  let rgb = []
  for (let i = 0; i < 3; ++i) {
    let color = Math.floor(Math.random() * 256).toString(16)
    color = color.length == 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}
Page({
  data: {
    activityId: null,
    childId: null,
    display: ''
  },

  // // 遮罩层隐藏
  applayVideo: function() {
    this.setData({
      flag: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },
  onShow: function() {
    if (!app.isLogin()) {
      this.getUserInfo();
    }
    this.setData({
      activityId: app.globalData.activityId ? app.globalData.activityId : null,
      childId: app.globalData.childId ? app.globalData.childId : null
    });
    this.initPage();
  },
  initPage: function() {
    this.queryLatelyActivity();
  },
  onChangeShowState: function() {
    var that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  getUserInfo: function () {
    let that = this;
    if (app.globalData.appUser != null) {
      return;
    }
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: app.httpUrl + '/common/getUserInfo',
            data: {
              code: res.code
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            method: "POST",
            success: function (res) {
              console.log("---getUser = " + JSON.stringify(res.data));
              if (res.data.code == '000') {
                app.globalData.appUser = res.data.data;
                app.globalData.openid = res.data.data.openid;
                that.initPage();
              }
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },
  queryLatelyActivity: function() {
    var that = this;
    var params = '';
    if (that.data.activityId) {
      params = '?activityId=' + that.data.activityId;
    }
    if(that.data.childId) {
      params = '?childId=' + that.data.childId;
    }
    // 小孩最近参加的活动
    wx.request({
      url: app.httpUrl + '/activity/queryLatelyActivity' + params,
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "GET",
      success: (res) => {
        if (res.data.code == '000') {
          if (res.data.data == null) {
            that.setData({
              hadData: false
            })
            return;
          }
          var Activity = res.data.data;
          var currTime = new Date().getTime();
          let percent = 0;
          if (Activity.endDate <= currTime) {
            percent = 100;
          } else {
            var totalDay = parseInt(Math.ceil((Activity.endDate - Activity.startDate) / 1000 / 60 / 60 / 24));
            var ingDay = parseInt(Math.ceil((currTime - Activity.startDate) / 1000 / 60 / 60 / 24));
            percent = parseInt((ingDay / totalDay) * 100);
          }
          that.setData({
            hadData: true,
            percent: percent,
            Activity: Activity
          })
          this.queryChildActInfo(Activity.activityId, Activity.childId);
          this.contentTaskView();
          this.queryMarineMember(Activity.marineId);
        }
      }
    })
  },
  contentTaskView() {
    WxParse.wxParse('contentTaskHtml', 'html', util.base64.decode(this.data.Activity.contentTask), this, 5);
  },
  queryChildActInfo: function(activityId, childId) {
    var that = this;
    // 查询小孩参与的活动信息
    wx.request({
      url: app.httpUrl + '/activity/queryChildActInfo',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      data: {
        activityId: activityId,
        childId: childId
      },
      success: (res) => {
        if (res.data.code == '000') {
          var data = res.data.data;
          data.startDate = util.formatDate(data.startDate, 'Y年M月D日');
          data.endDate = util.formatDate(data.endDate, 'Y年M月D日');
          that.setData({
            ChildActInfo: data
          });
          this.queryActImageList(data.marineId);
          this.queryActVideoList(data.marineId);
        }
      }
    })
  },
  queryMarineMember: function(marineId) {
    let that = this;
    wx.request({
      url: app.httpUrl + '/activity/queryMarMemList/' + marineId,
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "GET",
      success: (res) => {
        that.setData({
          memberlist: res.data.data
        })
      }
    })
  },
  queryActVideoList: function(marineId) {
    // 视频
    let that = this;
    wx.request({
      url: app.httpUrl + '/activity/live/queryListByPage',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      data: {
        marineId: marineId,
        page: 1,
        rows: 2,
        liveType: "video"
      },
      method: "POST",
      success: (res) => {
        var list = res.data.data.results;
        for (var i in list) {
          for (var j in list[i].attachList) {
            if (j == 0) {
              list[i].firstVideoUrl = app.imgUrl + list[i].attachList[j].attachUrl;
              list[i].firstThumbUrl = app.imgUrl + list[i].attachList[j].thumbAttachUrl;
            }
          }
        }
        that.setData({
          videolist: list
        })
      }
    })
  },
  queryActImageList: function(marineId) {
    // 活动图片
    let that = this;
    wx.request({
      url: app.httpUrl + '/activity/live/queryListByPage',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      data: {
        marineId: marineId,
        page: 1,
        rows: 2,
        liveType: "image",
      },
      method: "POST",
      success: (res) => {
        var list = res.data.data.results;
        for(var i in list) {
          for (var j in list[i].attachList) {
            if(j == 0) {
              list[i].firstImg = app.imgUrl + list[i].attachList[j].attachUrl;
            }
            list[i].attachList[j].attachUrl = app.imgUrl + list[i].attachList[j].attachUrl;
          }
        }
        that.setData({
          imagelist: list
        })
      }
    })
  },
  marinePreviewImage: function(event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    var list = [src];
    wx.previewImage({
      current: src, // 当前显示图片的http链接 
      urls: list // 需要预览的图片http链接列表     
    })
  },
  memberPreviewImage: function(event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    var list = [];
    for (var i in this.data.memberlist) {
      list[i] = app.imgUrl + this.data.memberlist[i].childImg;
    }
    wx.previewImage({
      current: src, // 当前显示图片的http链接 
      urls: list // 需要预览的图片http链接列表     
    })
  },
  // 图片预览
  previewImage: function(event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    var idx = event.currentTarget.dataset.idx;
    var list = this.data.imagelist[idx].attachList;
    var urls = [];
    for(var i in list) {
      urls.push(list[i].attachUrl);
    }
    wx.previewImage({
      current: src, // 当前显示图片的http链接 
      urls: urls // 需要预览的图片http链接列表     
    })
  },
  playVideo(e) {
    let index = e.currentTarget.dataset.index;
    let list = this.data.videolist;
    list.forEach(n => {
      n.isPlaying = false;
    })
    list[index].isPlaying = true;
    this.setData({
      videolist: list
    })
    let videoContext = wx.createVideoContext('video-' + index)
    videoContext.play()
  },
  inputValue: '',
  data: {
    src: '',
    bindInputBlur: function(e) {
      this.inputValue = e.detail.value
    },
    bindButtonTap: function() {
      var that = this
      wx.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 60,
        camera: ['front', 'back'],
        success: function(res) {
          that.setData({
            src: res.tempFilePath
          })
        }
      })
    },
    bindSendDanmu: function() {
      this.videoContext.sendDanmu({
        text: this.inputValue,
        color: getRandomColor()
      })
    },
  }
})